﻿using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using WPFSYN.Model;
using Resource;

namespace WPFSYN.Quartz
{
    [DisallowConcurrentExecution]
    [PersistJobDataAfterExecution]
    public class MyJob : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                JobDataMap dataMap = context.JobDetail.JobDataMap;
                string processName = dataMap.GetString("processName");
                SynchronizeJob.doSyncProcess(context, processName);
            }
            catch (Exception ex)
            {
                JobExecutionException exception = new JobExecutionException(ex);
                exception.Source = context.JobDetail.Description;
                exception.UnscheduleFiringTrigger = true;
                //throw ex;
            }
        }
    }

    public class SynchronizeJob
    {
        public static Write MyWrite;

        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
        /// <summary>      
        /// 释放内存      
        /// </summary>      
        public static void ClearMemory()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
            }
        }
        public static Result GetProcessor(string type, List<JsonData> list)
        {
            var api = list.Find(t => t.NodeName.Equals(type)).WebApi;
            List<object> paramelist = new List<object>();
            foreach (var item in api.Parameter)
            {
                paramelist.Add(item.Key);
            }
            BaseProcessor baseProcessor = FactoryService.GetProcessorFactory(type.ToUpper());
            //return baseProcessor.PushSend(api.Url, api.Method.ToUpper(), api.ContentType, paramelist);
            return new Result(true);

        }

        public static void doSyncProcess(IJobExecutionContext context, string process)
        {
            var time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            try
            {
                var result = GetProcessor(process, MainWindow.list);
                switch (result.Status)
                {
                    case 0:
                        MyWrite(process, string.Format(SynMsg.SynFai, time, result.ReturnMessage));
                        break;
                    case 1:
                        MyWrite(process, string.Format(SynMsg.SynSuccess, time));
                        break;
                    case 2:
                        MyWrite(process, string.Format(SynMsg.NoSynData, time));
                        break;
                }
                ClearMemory();
            }
            catch (Exception ex)
            {
                MyWrite(process, string.Format(SynMsg.SynErr, time));
                //LogHelper.Log(LogTarget.File, $"接口{process}：时间：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},错误:{ex.Message}");
                ClearMemory();
            }
        }
    }
}
